package com.comdev.ctrls;

import com.comdev.biz.FileBiz;
import com.comdev.common.Reps;
import com.comdev.common.WebPath;
import com.comdev.consts.ConstSys;
import com.comdev.exceptions.CommonOut;
import com.comdev.orm.jdbc.DbKit;
import com.comdev.ut.date.DatetimeUT;
import com.comdev.ut.string.StringUT;
import com.comdev.vos.t_file;
import com.comdev.vos.t_login;
import com.dbutils.QueryHelper;
import org.nutz.lang.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: gnoloahs
 * Date: 2013-04-24
 * Time: 上午9:15
 */

@Controller
@RequestMapping("file")
@SessionAttributes("curuser")
public class file
{

    @Autowired
    private FileBiz fileBiz;

    @RequestMapping("upload")
    @ResponseBody
    /**
     *  28,http://phpcms.com/up...884.ppt,ppt,UML基础教程.ppt
     */
    public String upload(@RequestParam("Filedata") MultipartFile infile, @ModelAttribute("curuser") t_login voLogon)
    {
        //取得文件名

        String filename = StringUT.ISO_UTF8(infile.getOriginalFilename());

        //文件后缀
        String suffix = filename.substring(filename.lastIndexOf('.') + 1, filename.length()).toLowerCase();

        //文件保存地址

        String savefilename = DatetimeUT.getNowstr() + DbKit.getDao().count(t_file.class) + "." + suffix;

        //创建文件夹
        String year = DatetimeUT.getYear(new Date());
        String MMdd = DatetimeUT.getMMdd(new Date());
        String filepath = WebPath.getUploadRootPath() + File.separator + year + File.separator + MMdd;
        String dbfilepath = year + File.separator + MMdd;
        if (!(new File(filepath).exists()))
        {
            new File(filepath).mkdirs();
        }

        try
        {
            infile.transferTo(new File(filepath + File.separator + savefilename));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        //存入数据库

        t_file vo = new t_file();
        vo.setObjid(StringUT.getUUID());
        vo.setFilename_(filename);
        vo.setFilesize_(new File(filepath + File.separator + savefilename).length());
        vo.setModifydate(DatetimeUT.getNow());
        vo.setSavepath_(dbfilepath + File.separator + savefilename);
        vo.setSuffix_(suffix);

        QueryHelper.insert(vo);

        boolean img = false;
        if (ConstSys.imgList.contains(vo.getSuffix_()))
        {
            img = true;
        }

        return vo.getObjid() + "," + "/file/down/" + vo.getObjid() + "" + "," + vo.getSuffix_() + "," + vo.getFilename_() + "," + img;//json data

    }

    @ResponseBody
    @RequestMapping("del")
    public Map del(@RequestParam("objid") String objid)
    {
        Map out = new HashMap<String, String>();
        try
        {
            fileBiz.del(objid);
        }
        catch (CommonOut e)
        {
            Reps.add(out, e);
            return out;
        }
        catch (Exception e)
        {
            Reps.add(out, e);
            return out;
        }
        Reps.success(out);
        return out;
    }


    @RequestMapping("down/{id}")
    public void down(@PathVariable("id") String fileid, HttpServletRequest request,
                     HttpServletResponse response)
    {

        t_file vo = DbKit.getDao().fetch(t_file.class, fileid);

        if (StringUT.isEmpty(vo))
        {
            try
            {
                response.setCharacterEncoding("UTF-8");
                Streams.writeAndClose(response.getWriter(), "文件id不存在于数据库中，" + fileid);
            }
            catch (Exception e)
            {

            }
        }

        String downLoadPath = WebPath.getUploadRootPath() + vo.getSavepath_();
        // 不存在返回异常
        if (StringUT.isEmpty(vo) || !(new File(downLoadPath).exists()))
        {
            throw new RuntimeException("指定的文件不存在");
        }

        if (vo.getSuffix_().equals("mp3"))
        {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

//            String filehouzui = new File(downLoadPath).getName();
//            filehouzui = filehouzui.substring(filehouzui.lastIndexOf(".")).toLowerCase().replace(".", "");
            try
            {
                long fileLength = new File(downLoadPath).length();
                response.setContentType("audio/x-mpeg");//需要设置文件流
                response.setHeader("Content-Length",
                        String.valueOf(fileLength));
                bis = new BufferedInputStream(new FileInputStream(downLoadPath));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff,
                        0,
                        buff.length)))
                {
                    bos.write(buff,
                            0,
                            bytesRead);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (bis != null)
                {
                    try
                    {
                        bis.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                if (bos != null)
                {
                    try
                    {
                        bos.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }


        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;


        try
        {
            long fileLength = new File(downLoadPath).length();
            response.setContentType("application/x-msdownload;");

            // 下面三个if中的fileName必须直接来自输入参数，没做任何处理。
            String fileName = vo.getFilename_();

            fileName = StringUT.UTF8_ISO(fileName);
            String head = "";
            if (StringUT.isIE(request))
            {
                fileName = URLEncoder.encode(StringUT.ISO_UTF8(fileName),
                        "UTF-8").replace("+",
                        "%20");
                head = "attachment; filename=" + fileName;
            } else if (StringUT.isChrome(request))
            {
                head = "attachment; filename=" + fileName;
            } else if (StringUT.isFirefox(request))
            {
                head = "attachment;filename=\"" + fileName + "\"";
            }

            //显示图片
            if (ConstSys.imgList.contains(vo.getSuffix_().toLowerCase()))
            {
                if (vo.getSuffix_().equals("jpg"))
                {
                    response.setContentType("image/jpeg");
                } else
                {
                    response.setContentType("image/" + vo.getSuffix_() + "");
                }
            }
            //下载文件
            else
            {
                response.setHeader("Content-disposition",
                        head);// 下载文件的时候
            }

            response.setHeader("Content-Length",
                    String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff,
                    0,
                    buff.length)))
            {
                bos.write(buff,
                        0,
                        bytesRead);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bis != null)
            {
                try
                {
                    bis.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }


}
